let stompClient = null;
setConnected(false);
$("#username").val("jack_" + new Date());

function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    if (connected) {
        $("#content").show();
        $("#send").show();
    } else {
        $(" #content").hide();
        $("#send").hide();
    }
    $("#greetings").html("");
}

function connect() {
    if (!$("#username").val()) {
        alert("请输入用户名");
        return;
    }
    let socket = new SockJS('/chat');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, connecting);
}

function connecting(frame) {
    setConnected(true);

    // subscribe方法用来订阅服务端发回来的消息
    stompClient.subscribe('/topic/greetings', receiveMsg);
}

/**
 * 接收服务器消息
 */
function receiveMsg(greeting) {
    showMsging(JSON.parse(greeting.body));
}

function disconnect() {
    if (stompClient !== null) {
        stompClient.disconnect();
        setConnected(false);
    }
}

function sendName() {
    stompClient.send("/app/hello", {}, JSON.stringify({
        "username" : $("#username").val(),
        "content" : $("#content").val()
    }));
}

function showMsging(message) {
    $("#msglist").append("<span>" + message.username + ":" + message.content + "</span><br/>");

    var div = document.getElementById('msglist');
    div.scrollTop = div.scrollHeight;
}

$(function() {
    $("#connect").click(function() {
        connect();
    });
    $("#disconnect").click(function() {
        disconnect();
    });
    $("#send").click(function() {
        sendName();
    });
});
